package uk.co.q3c.deplan.client.ui.view;

import java.util.EnumMap;
import java.util.logging.Logger;

import uk.co.q3c.deplan.client.domain.DomainKind;
import uk.co.q3c.deplan.client.util.HistoryTokenRecord;

/**
 * A view is only instantiated when needed, and it is re-used rather than disposed and re-created. To add a new view, an entry is needed in
 * the static initialiser for both {@link #viewCache} and {@link #viewIndexMap}, and the switch statement in {@link #view(String)} extended.
 * 
 * @author David Sowerby 3 May 2010
 * 
 */
public class ViewManager {
	protected static final Logger logger = Logger.getLogger(ViewManager.class.getName());
	private ViewCreator viewCreator;

	private static EnumMap<Viewtags, Q3CoreView> viewCache = new EnumMap<Viewtags, Q3CoreView>(Viewtags.class);

	public ViewManager() {
		super();
	}

	/**
	 * Returns an instantiated view for the supplied viewTag. This will be a cached view if there is one, and if not a new one is created.
	 * 
	 * @param viewTag
	 * @return
	 */
	public Q3CoreView view(Viewtags viewTag) {
		if (viewCreator == null) {
			logger.fine("ViewCreator has not been set");
			return null;
		}
		Q3CoreView view = viewCache.get(viewTag);
		if (view == null) {
			view = viewCreator.createView(viewTag);
			viewCache.put(viewTag, view);
			return view;
		} else {
			return view;
		}

	}

	public void newHistoryItem(Q3CoreView view, boolean fireEvent) {
		viewCreator.newHistoryItem(tokenAsString(view), fireEvent);
	}

	public String tokenAsString(Q3CoreView view) {
		String s = token(view).toString();
		return s;
	}

	public HistoryTokenRecord token(Q3CoreView view) {
		HistoryTokenRecord htr = new HistoryTokenRecord();
		htr.id = view.getViewedObjectId();
		if (view.getPresenter()
				.getObjectInView() == null) {
			htr.kind = DomainKind.Unknown;
		} else {
			htr.kind = view.getPresenter()
					.getObjectInView()
					.getKind();
		}
		htr.viewName = view.viewTag();
		return htr;
	}

	public ViewCreator viewCreator() {
		if (viewCreator == null) {
			logger.severe("View creator has not been set");
		}
		return viewCreator;
	}

	public void setViewCreator(ViewCreator viewCreator) {
		this.viewCreator = viewCreator;
	}

	public long getViewedObjectId(Q3CoreView view) {
		if (view.getPresenter()
				.getObjectInView() == null) {
			return 0;
		}
		Long i = view.getPresenter()
				.getObjectInView()
				.getKeyId();
		if (i == null) {
			return 0;
		} else {
			return i;
		}

	}

}
